<template>
  <view class="container">
    
    <Card class="form-card">
      <view class="avatar-section">
        <view class="avatar-upload" @click="uploadAvatar">
          <view class="avatar-wrapper">
            <image v-if="form.avatar" :src="form.avatar" class="avatar-img" />
            <view v-else class="avatar-placeholder">头像</view>
            <view class="avatar-overlay"><text>更换</text></view>
          </view>
        </view>
      </view>

      <view class="list">
        <view class="list-item">
          <text class="item-label">昵称</text>
          <input class="item-input" type="text" placeholder="请输入昵称" v-model="form.nickname" />
        </view>
        
        <view class="list-item is-readonly">
          <text class="item-label">用户名</text>
          <text class="picker-text readonly">{{ form.username || '-' }}</text>
        </view>

        <view class="list-item">
          <text class="item-label">性别</text>
          <picker :range="genderOptions" :value="genderIndex" @change="onGenderChange">
            <view class="picker-text">{{ genderOptions[genderIndex] }}</view>
          </picker>
        </view>

        <view class="list-item">
          <text class="item-label">生日</text>
          <picker mode="date" :value="birthday" :end="today" start="1950-01-01" @change="onBirthdayChange">
            <view class="picker-text">{{ birthday || '请选择' }}</view>
          </picker>
        </view>

        <view class="list-item">
          <text class="item-label">所在地</text>
          <picker mode="region" :value="region" @change="onRegionChange">
            <view class="picker-text">{{ regionText || '请选择' }}</view>
          </picker>
        </view>

        <view class="list-item multiline">
          <text class="item-label">简介</text>
          <textarea class="item-textarea" placeholder="我有一个超级无敌可爱的猫猫" v-model="form.bio" />
        </view>
      </view>
    </Card>
    <view class="bottom-bar">
      <Button class="bottom-btn" type="primary" text="提交修改" :loading="loading" @click="handleSubmit" />
    </view>
  </view>
</template>

<script>
import { getStorage, setStorage } from '../../utils/storage.js';
import { services } from '../../api/index.js';
const userAPI = services.user;

export default {
  data() {
    return {
      form: {
        avatar: '',
        username: '',
        nickname: '',
        contact: '',
        bio: ''
      },
      genderOptions: ['保密', '男', '女'],
      genderIndex: 0,
      birthday: '',
      today: '',
      region: [],
      regionText: '',
      loading: false
    };
  },
  onLoad() {
    // 从本地缓存预填（由个人中心进入时一般已缓存）
    const cached = getStorage('userInfo') || {};
    this.form.avatar = cached.avatar || cached.imgPath || '';
    this.form.username = cached.username || cached.userEmail || cached.userPhone || '';
    this.form.nickname = cached.nickname || cached.userNike || '';
    this.form.contact = cached.userEmail || cached.userPhone || cached.username || '';
    this.form.bio = cached.userProfile || '';
    // 预设今天
    const d = new Date();
    const yyyy = d.getFullYear();
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const dd = String(d.getDate()).padStart(2, '0');
    this.today = `${yyyy}-${mm}-${dd}`;
  },
  
  methods: {
    uploadAvatar() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          // 暂不上传至后端，仅作本地预览（后端存储准备好后接入）
          this.form.avatar = res.tempFilePaths[0];
          uni.showToast({
            title: '头像已选择（暂不上传）',
            icon: 'success'
          });
        }
      });
    },
    
    onGenderChange(e) {
      this.genderIndex = Number(e.detail.value || 0);
    },
    onBirthdayChange(e) {
      this.birthday = e.detail.value;
    },
    onRegionChange(e) {
      this.region = e.detail.value || [];
      this.regionText = (this.region && this.region.length) ? this.region.join(' ') : '';
    },

    async handleSubmit() {
      if (!this.form.nickname) {
        uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        });
        return;
      }
      
      if (!this.form.contact) {
        uni.showToast({
          title: '请输入联系方式',
          icon: 'none'
        });
        return;
      }
      // 基础格式校验（邮箱或大陆手机号）
      const emailRegex = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
      const phoneRegex = /^1[3-9]\d{9}$/;
      const isEmail = emailRegex.test(this.form.contact);
      const isPhone = phoneRegex.test(this.form.contact);
      if (!isEmail && !isPhone) {
        uni.showToast({ title: '联系方式格式不正确', icon: 'none' });
        return;
      }
      
      // 组织后端所需字段
      const payload = {
        userNike: this.form.nickname,
        userProfile: this.form.bio
      };
      if (isEmail) payload.userEmail = this.form.contact;
      if (isPhone) payload.userPhone = this.form.contact;
      // 性别/生日/地区若后端字段确定可在此补充

      try {
        this.loading = true;
        const resp = await userAPI.updateUserInfo(payload);
        // 同步本地缓存，便于返回后展示
        const updated = {
          username: isEmail ? this.form.contact : (isPhone ? this.form.contact : this.form.username),
          nickname: this.form.nickname,
          avatar: this.form.avatar,
          userProfile: this.form.bio,
          userEmail: isEmail ? this.form.contact : '',
          userPhone: isPhone ? this.form.contact : ''
        };
        // 合并旧信息
        const cached = getStorage('userInfo') || {};
        setStorage('userInfo', { ...cached, ...updated });
        uni.showToast({ title: '信息保存成功', icon: 'success' });
        setTimeout(() => {
          uni.navigateBack();
        }, 800);
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: $spacing-base;
  background-color: $background-color;
  min-height: 100vh;
  padding-bottom: 160rpx; // 预留底部按钮空间
}

.header {
  text-align: center;
  margin-bottom: $spacing-lg;
  padding: $spacing-xl 0;
}

.title {
  font-size: $font-size-xl;
  font-weight: bold;
  color: $text-primary;
  display: block;
  margin-bottom: $spacing-sm;
}

.subtitle {
  font-size: $font-size-sm;
  color: $text-secondary;
}

.form-card { margin-bottom: $spacing-lg; border-radius: 24rpx; overflow: hidden; box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.04); background-color: #fff; padding: $spacing-base; }

.avatar-section { margin-bottom: $spacing-lg; display: flex; justify-content: center; }

.label {
  display: block;
  font-size: $font-size-base;
  color: $text-primary;
  margin-bottom: $spacing-sm;
}

.avatar-upload { display: flex; flex-direction: column; align-items: center; justify-content: center; }
.avatar-tip { color: $text-tertiary; font-size: $font-size-sm; margin-left: $spacing-base; }

.avatar-wrapper { width: 140rpx; height: 140rpx; border-radius: 50%; margin: 0 auto; overflow: hidden; background-color: $primary-color; display: flex; align-items: center; justify-content: center; position: relative; }

.avatar-img {
  width: 100%;
  height: 100%;
}

.avatar-placeholder {
  color: #fff;
  font-size: $font-size-sm;
}

.avatar-overlay { position: absolute; bottom: 0; left: 0; right: 0; height: 40rpx; background: rgba(0,0,0,0.25); display: flex; align-items: center; justify-content: center; color:#fff; font-size: 22rpx; }

.form-group {
  margin-bottom: $spacing-lg;
}

.input, .textarea {
  width: 100%;
  padding: $spacing-base;
  border: 1rpx solid $text-tertiary;
  border-radius: $border-radius-base;
  font-size: $font-size-base;
  box-sizing: border-box;
  background-color: #fff;
}

.input {
  height: 80rpx;
}

.textarea {
  height: 160rpx;
  min-height: 160rpx;
}

.input:focus, .textarea:focus { border-color: $primary-color; outline: none; }
.hint { display: block; margin-top: $spacing-xs; color: $text-tertiary; font-size: $font-size-sm; }
.section-title { display:block; font-size: $font-size-base; color: $text-secondary; margin-bottom: $spacing-sm; }
.group { margin-bottom: $spacing-lg; }

.submit-btn { width: 100%; margin-top: $spacing-xl; }
.bottom-bar {
  position: fixed;
  left: 0; right: 0; bottom: 0;
  padding: $spacing-base $spacing-base calc($spacing-base + env(safe-area-inset-bottom));
  background-color: transparent; // 避免白底溢出屏幕
  box-shadow: none;
}
.bottom-btn { border-radius: 16rpx; }

/* 列表样式 */
.list { background-color: #fff; border-radius: 16rpx; overflow: hidden; }
.list-item { display: flex; align-items: center; padding: 28rpx $spacing-base; border-bottom: 1rpx solid $border-color; }
.list-item:last-child { border-bottom: 0; }
.item-label { width: 160rpx; color: $text-secondary; font-size: $font-size-base; }
.item-input { flex: 1; text-align: right; color: $text-primary; font-size: $font-size-base; }
.picker-text { flex: 1; text-align: right; color: $text-primary; }
.readonly { color: $text-tertiary; }
.multiline { align-items: flex-start; }
.item-textarea { flex: 1; min-height: 120rpx; text-align: right; padding: 0; border: none; background: transparent; }
</style>